package main

import (
	"flag"
	log "github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql" //驱动包
	"html/template"
	"io"
	"os"
	"path/filepath"
	"strings"
	"test/controllers"
	"test/helpers"
	"test/models"
	"test/system"
	//_ "github.com/jinzhu/gorm/dialects/sqlite"
	"test/middlewares"
)

func main() {

	configFilePath := flag.String("C", "conf/conf.yaml", "config file path")
	flag.Parse()

	log.Info("main.go---打印Log ")
	if err := system.LoadConfiguration(*configFilePath); err != nil {
		log.Critical("err parsing config log file", err)
		return
	}

	db, err := models.InitDB()
	if err != nil {
		//seelog.Critical("err open databases", err)
		return
	}
	defer db.Close()

	/*db, _ := gorm.Open("sqlite3", "./gorm.db")
	defer db.Close()*/

	/*db, err := gorm.Open("mysql",
		"root:123456@/test?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		fmt.Println(err)
		return
	}else {
		fmt.Println("connection succedssed")
	}
	defer db.Close()*/

	r := gin.Default()

	setTemplate(r)
	SetSessions(r)

	//中间件 设置(c.Set)用户信息
	r.Use(middlewares.SharedData()) //

	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	//r.LoadHTMLGlob("templates/*")
	//r.LoadHTMLGlob("./views/**/*")
	//r.Static("/static", filepath.Join(getCurrentDirectory(), "./static"))
	r.Static("/static", "./static")

	//路由
	r = SetupRouter(r)
	//404
	r.NoRoute(controllers.Handle404)

	//最后
	r.Run(":8088") // 监听并在 0.0.0.0:8080 上启动服务
	//http.ListenAndServe(":8088", r)
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Critical(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func setTemplate(engine *gin.Engine) {

	funcMap := template.FuncMap{
		"dateFormat": helpers.DateFormat,
		"substring":  helpers.Substring,
		"isOdd":      helpers.IsOdd,
		"isEven":     helpers.IsEven,
		"truncate":   helpers.Truncate,
		"add":   helpers.Add,
		"minus": helpers.Minus,
		//"listtag":    helpers.ListTag,
	}

	engine.SetFuncMap(funcMap)
	engine.LoadHTMLGlob("./views/**/*")

}


